<script setup>
import listApis from '@/apis/list.js'
import questionApis from '@/apis/question.js'
import useLocalStore from '@/stores/local';
import { ElMessageBox } from 'element-plus';
import videoApis from '@/apis/video.js';
import config from '@/config/index.js';
import { secondFormat} from '@/utils/format.js'
import { Back,ChatDotRound  } from '@element-plus/icons-vue'
import useUserStore from '@/stores/user.js'

const router = useRouter();
const instance=getCurrentInstance()
const route = useRoute();
const listItems = ref([])
const localStore = useLocalStore();
const loading = ref(false);
const elTreeNode = ref(null)
const drawer = ref(false)
const resources = ref([])
const lastVid = ref(null)
const userStore = useUserStore()
const emit = defineEmits(['goBack'])
const props=defineProps({
  columnId:{
    type:[String,Number],
    required:true
  }
})

init()


async function init() {
  loading.value = true
  try {
    const res = await videoApis.chapterList({
      params: {
        // columnId: userStore.selectCategory.,
        industryCode:userStore.selectCategory.industryCode,
        columnId:props.columnId,
        examId:userStore.selectCategory.examId,
        categoryId:userStore.selectCategory.categoryId,
      }
    })
    // questionApis.getChapterRecordsIds()   getChapterRecords
    if (res.data.length == 0) {
      loading.value = false
      return
    }
    listItems.value = res.data.map(e => {
      return {
        ...e,
        isLeaf: false,
        topChapterId: e.id
      }
    })
  } catch (err) {

  }
  loading.value = false

}


function goTopic(data) {
  if (data.doCount) {
    ElMessageBox.confirm('是否继续练习', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '重新开始',
      showClose: false,
      type: 'warning'
    }).then(() => {
      router.push({
        path: `/question/chapter/practice`, query: {
          categoryId: route.query.categoryId, columnId: route.query.columnId,
          id: data.id,
          name: data.name,
          dc: data.dc,
          ec: data.ec,
          cc: data.cc,
        }
      })
    }).catch(_ => {
      router.push({
        path: `/question/chapter/practice`, query: {
          categoryId: route.query.categoryId, columnId: route.query.columnId,
          id: data.id,
          name: data.name,
          restart: true
        }
      })
    })
  } else {
    router.push({
      path: `/question/chapter/practice`, query: {
        categoryId: route.query.categoryId, columnId: route.query.columnId,
        id: data.id,
        name: data.name,
      }
    })
  }


}
function load(node, resolve) {
  if (node.level != 0) {
    if (node.data.leaf) {
      videoApis.list({
        params: {
          ChapterId: node.data.id,
          industryCode:userStore.selectCategory.industryCode,
          columnId:props.columnId,
          examId:userStore.selectCategory.examId,
          categoryId:userStore.selectCategory.categoryId,
        }
      }).then(res => {
        resolve(res.data.map(e => {
          e.topChapterId = node.data.topChapterId
          e.isLeaf = true
          e.doPercent = (e.watchDuration / e.duration) * 100
          e.watchTime = secondFormat(e.watchDuration)
          e.totalTime = secondFormat(e.duration)
          return e
        }))
      })

    } else {
      listApis.childChapter({ params: { pid: node.data.id } }).then(async res => {
        resolve(res.data.map(e => {
          return {
            ...e,
            topChapterId: node.data.topChapterId,
            isLeaf: false,
          }
        }))
      })
    }
  }
  resolve([])
}

function showResource(nodeData, props) {
  videoApis.handoutList({
    params: {
      videoId: nodeData.id
    }
  }).then(res => {
    resources.value = res.data
    drawer.value = true
  })

}

function download(row) {
  videoApis.addFrequency({
    id: row.id
  })
  fetch(config.prefix_image + row.url, {
    method: 'GET',
  })
      .then(response => response.blob())
      .then(blob => {
        // 创建一个虚拟的链接元素，模拟点击下载
        const link = document.createElement('a');
        link.style.display = 'none';
        const url = window.URL.createObjectURL(blob);
        link.href = url;
        link.download = row.name;
        document.body.appendChild(link);

        // // 模拟点击
        link.click();
        // // 移除虚拟链接元素
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url)
      })
}
function preview(row) {
  window.open(config.prefix_image + row.url)
}
function goBack(){
  emit('goBack')
}
function formatTime(percentage,data){
  return data.totalTime+'/'+ data.watchTime;
}

function goToPlay(nodeData, props1) {

  // console.log(instance)
  // return;
  router.push({
    path: `/courseVideo/chapter/videos`, query: {
      vid: nodeData.aliyunVideoId,
      columnId: props.columnId,
      topChapterId: nodeData.topChapterId,
      videoId: nodeData.id,
      watchDuration: nodeData.watchDuration
    }
  })
}
</script>

<template>
    <div class="ChapterVideo-container">
      <el-button type="text" @click="goBack">
        <el-icon color="#409eff" >
          <Back />
        </el-icon>
        返回
      </el-button>
      <div class="tree-container">
        <el-tree ref="elTreeNode" node-key="id" v-loading="loading" :data="listItems" :load="load" lazy
                 :props="{ label: 'name', isLeaf: 'isLeaf' }" :height="408">
          <template #default="{ node, data }">
            <div class="chapter-video-item" :class="{
            leaf: data.isLeaf,
          }">
              <div class="name chapterWrap" v-if="!data.isLeaf">
                <span>{{ data.name }}</span>
              </div>
              <div  class="chapterWrap-flex" v-else>
                <div class="name chapterWrap">
                  <span>{{ data.name }}</span>
                </div>
                <div class="info-icon">
                  <el-tooltip :content="data.name"
                              trigger="click"
                              placement="top-start"><ChatDotRound/></el-tooltip>
                </div>
              </div>
              <div class="my-progress-container"  v-if="data.isLeaf">

                <el-progress :text-inside="true" :format="(v)=>formatTime(v,data)" striped :stroke-width="26" :percentage="data.doPercent" />
              </div>

              <div v-if="data.isLeaf" class="">
                <el-button type="primary" @click="showResource(data, node)" text>
                  资料
                </el-button>
                <el-button type="primary" @click="goToPlay(data, node)" text>
                  播放
                </el-button>
              </div>
            </div>
          </template>
        </el-tree>

      </div>
      <el-drawer v-model="drawer" direction="rtl" size="40%">
        <el-table :data="resources">
          <el-table-column label="文件名" prop="name" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="180px">
            <template #default="{ row }">
              <div>
                <el-button type="primary" @click="download(row)">下载</el-button>
                <el-button type="primary" @click="preview(row)">预览</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>
    </div>
</template>

<style scoped>
.ChapterVideo-container{
  padding: 22px;
}
.chapter-video-item.leaf{
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 30px;
}
.chapter-video-item.leaf .chapterWrap{
  position: relative;
  width: 300px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.chapterWrap-flex{
  display: flex;
}
.info-icon{
  width: 12px;
  height:12px;
  align-self: start;
}
.my-progress-container{
  width: 300px;
}
.ChapterVideo-container ::v-deep(.el-tree-node__content) {
  height: 40px;
  line-height: 40px;
}
.tree-container {
  max-height: 500px;
  overflow-y: auto;
  padding: 10px;
}
</style>